//
//  BowenListViewController.m
//  YiqiMobile
//
//  Created by henry on 13-4-2.
//  Copyright (c) 2013年 henry. All rights reserved.
//

#import "TogetherSecondViewController.h"
#import "Config.h"
#import "Utility.h"
#import "TogetherSecondViewCell.h"
#import "HomePageViewController.h"
#import "AppDelegate.h"
#import "AddBowenViewController.h"
#import "CustomNavigationController.h"
#import "JSON.h"
#import "BowenPreviewViewController.h"
#import "DefineAction.h"
#import "MBProgressHUD.h"


@interface TogetherSecondViewController ()
-(void) onclickbuttonAction:(UIButton*) sender;//加入圈子或者新建博文
@end

@implementation TogetherSecondViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.view.backgroundColor=[UIColor whiteColor];
        // Custom initialization
    }
    return self;
}
-(void) loadData:(NSDictionary*) param{
     
     self.quanziDict=param;
     self.navigationItem.titleView=[Utility getTitleView:[self.quanziDict objectForKey:@"str2"]];
    [self loadUserInfoFromServer];
}

-(void) loadUserInfoFromServer{
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
    NSString *userId=[[NSUserDefaults standardUserDefaults] objectForKey:USERID];
    NSString *url=[NSString stringWithFormat:@"%@/%@?e.e0=%@&u.u0=%@",[Utility  getServerUrl],GETQUANZIINFOACTION,[self.quanziDict objectForKey:@"str1"],userId];
    self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:nil andFile:nil];
    [[MBProgressHUD showHUDAddedTo:self.view animated:YES] setLabelText:LOADING_TITLE_DEFAULT];
    [self.request startLoadData];
}

/*
 e.e0	N	需要加入的圈子ID
 u.u0	N	需要加入的用户ID
 str1	Y	接受到的邀请码  没有就传 “”
 str2	Y	需要审核的话 申请的理由  没有就传 “”
 */
-(void) joinQuanzi{
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
    NSString *userId=[[NSUserDefaults standardUserDefaults] objectForKey:USERID];
    NSString *url=[NSString stringWithFormat:@"%@/%@?u.u0=%@&e.e0=%@&str1=%@&str2=%@",[Utility  getServerUrl],QUANZI_JOINACTION,userId,[self.quanziDict objectForKey:@"str1"],@"",@""];
    self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:nil andFile:nil];
    [[MBProgressHUD showHUDAddedTo:self.view animated:YES] setLabelText:LOADING_TITLE_DEFAULT];
    [self.request startLoadData];
}


//圈子草稿
-(void) getallcaogao:(int) page{
    if (page<2) {
        [self.arrayList removeAllObjects];
    }
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
    NSString *userId=[[NSUserDefaults standardUserDefaults] objectForKey:USERID];
    NSString *url=[NSString stringWithFormat:@"%@/%@?id=%@&u.u0=%@&type=%d",[Utility  getServerUrl],QUANZICAOGAOACTON,[self.quanziDict objectForKey:@"str1"],userId,page];
    self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:nil andFile:nil];
    [[MBProgressHUD showHUDAddedTo:self.view animated:YES] setLabelText:LOADING_TITLE_DEFAULT];
    [self.request startLoadData];
}

- (void)requestFinished:(id)context{
    [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
    @try{
        NSDictionary *result=[context JSONValue];
        if (result!=nil&&[[result  objectForKey:@"code"] integerValue]==0) {
            if ([[result  objectForKey:@"method"] isEqualToString:GETQUANZIINFOACTION]) {
                self.userDict=[result objectForKey:@"data"];
                [self getallcaogao:1];
            }else if([[result  objectForKey:@"method"] isEqualToString:QUANZICAOGAOACTON]){
                [self.arrayList addObjectsFromArray:[result objectForKey:@"list"]];
                [self.mytableView reloadData];
            }else if ([[result  objectForKey:@"method"] isEqualToString:QUANZI_JOINACTION]) {//加入
                [Utility customAlertWithMsg:@"您已成功加入此圈子" andTitle:ALRRTTITLE andDelagate:nil];
                [self loadUserInfoFromServer];
            }
            
        }else{
            [Utility customAlertWithMsg:PROCESSERROE andTitle:ALRRTTITLE andDelagate:nil];
        }
    }@catch (NSException *e) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
    }
}

- (void)requestFailed:(id)context error:(NSString *)error{
    [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:NO];
    [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
}


- (void)viewDidLoad{
    [super viewDidLoad];
   
   
    //导航栏左边按钮
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:[Utility customButton:self action:@selector(onClickAction:) normalImage:@"pushButton_normal.png" lightedImage:@"pushButton_hover.png" frame:CGRectMake(0, 0, 35, 35) title:nil tag:PUSHMENUBUTTONTAG]];
    //导航栏右边按钮
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:[Utility customButton:self action:@selector(onClickAction:) normalImage:@"moreButton_normal.png" lightedImage:@"moreButton_hover.png" frame:CGRectMake(0, 0, 35, 35) title:nil tag:PUSHMENUBUTTONTAG+1]];
    
	// Do any additional setup after loading the view.
    float tableHeight=0.0f;
    if (!iPhone5) {
        tableHeight=367;
    }else{
        tableHeight=455;
    }
    
    CGRect tableViewFrame=CGRectMake(0, 0, UISCREEN_WIDTH, tableHeight);
    self.mytableView.frame=tableViewFrame;
    self.mytableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, tableHeight) style:UITableViewStylePlain];
    self.mytableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    self.mytableView.delegate=self;
    self.mytableView.dataSource=self;
    //self.mytableView.showsVerticalScrollIndicator=NO;
    [self.view addSubview:self.mytableView];
    self.arrayList=[NSMutableArray array];
    [self tableviewHeader];

}
-(void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    self.hidesBottomBarWhenPushed=NO;
    [app.tabBarController hideExistingTabBar];
    app.tabBarController.tabBarView.hidden=NO;
    HomePageViewController *homePageViewController=(HomePageViewController*)[[[self.tabBarController.viewControllers objectAtIndex:0] viewControllers] objectAtIndex:0];
    homePageViewController.isShowLevelPop=YES;
    UIView *rightPopView=[self.view  viewWithTag:HOMEPAGELPV];
    [rightPopView removeFromSuperview];
}

-(void) onClickAction:(UIButton*) sender{
    HomePageViewController *homePageViewController=(HomePageViewController*)[[[self.tabBarController.viewControllers objectAtIndex:0] viewControllers] objectAtIndex:0];
    [homePageViewController  performSelector:@selector(onClickAction:) withObject:sender];
    
}

-(void) tableviewHeader{
    UIView *header=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 175)];
    UIImageView *background=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 175)];
    background.tag=800;
    background.userInteractionEnabled=YES;
    [header addSubview:background];
    
    UIImageView *logo=[[UIImageView alloc] initWithFrame:CGRectMake(20, 125, 82, 82)];
    logo.tag=801;
    [header addSubview:logo];
    
    UILabel *nickname=[Utility detailTextLabel:CGRectMake(105, 185, 100, 14)andFontSize:9.0f];
    nickname.tag=802;
    nickname.font=[UIFont fontWithName:FONT_FAMILY size:9.0f];
    nickname.textColor=UIColorFromRGB(0x000000);
    [header addSubview:nickname];
    UIButton *addbowenButton=[Utility customButton:self action:@selector(onclickbuttonAction:) normalImage:@"addbowen.png" lightedImage:@"addbowen.png" frame:CGRectMake(225, 175, 89, 30) title:nil tag:BUTTONQUANZITAG];
    addbowenButton.hidden=YES;
    [header addSubview:addbowenButton];
    UIButton *joinquanziButton=[Utility customButton:self action:@selector(onclickbuttonAction:) normalImage:@"joinquanzi.png" lightedImage:@"joinquanzi.png" frame:CGRectMake(235, 175, 79, 30) title:nil tag:BUTTONQUANZITAG+1];
    joinquanziButton.hidden=YES;
    [header addSubview:joinquanziButton];
    header.backgroundColor=[UIColor whiteColor];
    self.tableCell0View=header;
}

-(void) showCell0Ofsection{
    UIImageView *background=(UIImageView*)[self.tableCell0View viewWithTag:800];
    UIImageView *logo=(UIImageView*)[self.tableCell0View viewWithTag:801];
    UILabel *nickname=(UILabel*)[self.tableCell0View viewWithTag:802];
    UIButton *addbowenButton=(UIButton*)[self.tableCell0View viewWithTag:BUTTONQUANZITAG];
    UIButton *joinquanziButton=(UIButton*)[self.tableCell0View viewWithTag:BUTTONQUANZITAG+1];
    background.image=[Utility imageNamed:@"quanzitopbg.png"];
    
    NSString *logoUrl=[self.userDict objectForKey:@"u.u6"];
    if (logoUrl&&logoUrl.length>0) {
        logo.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",[Utility getServerUrl],logoUrl]]]];
    }else{
        logo.image=[Utility imageNamed:@"qz_logo.png"];
    }
    int role=[[self.quanziDict objectForKey:@"count1"] integerValue];
    nickname.text=[NSString stringWithFormat:@"%@",[Utility getUserRole:role]];
    if (role<3) {
        addbowenButton.hidden=NO;
        joinquanziButton.hidden=YES;
    }else{
        addbowenButton.hidden=YES;
        joinquanziButton.hidden=NO;
    }

}

//表视图委托
#pragma mark - Tableview datasource & delegates
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    [self showCell0Ofsection];
    return self.tableCell0View;
    }

//指定有多少个分区(Section)，默认为1
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.arrayList count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
        return 205.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 58.0f;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentity = @"bowenViewCell";
    TogetherSecondViewCell *cell = (TogetherSecondViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentity];
    if (cell ==  nil) {
        cell = [[TogetherSecondViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentity];
    }
    NSDictionary *dict=[self.arrayList objectAtIndex:indexPath.row];
    cell.content.text=[dict objectForKey:@"str2"];
    cell.detailContent.text=[NSString stringWithFormat:@"供稿:%@  评论:%@",[dict objectForKey:@"count7"],[dict objectForKey:@"count5"]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    /*BowenPreviewViewController *bowen=[[BowenPreviewViewController alloc] initWithNibName:nil bundle:nil];
    NSDictionary *dcit=[self.arrayList objectAtIndex:indexPath.row];
    [bowen loadDataFromServer:[dcit objectForKey:@"str1"]];
    [self.navigationController pushViewController:bowen animated:YES];*/
    
}

-(void) onclickbuttonAction:(UIButton*) sender{
    if(sender.tag==BUTTONQUANZITAG){//新建博文
        AddBowenViewController *addBowenViewController=[[AddBowenViewController alloc] initWithNibName:nil bundle:nil];
        addBowenViewController.quanziId=[self.quanziDict objectForKey:@"str1"];
        [self.navigationController pushViewController:addBowenViewController animated:YES];
       
    }else if(sender.tag==BUTTONQUANZITAG+1){//加入圈子
        [self joinQuanzi];
    }
    
}


// 在iOS6下已废弃
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return interfaceOrientation==UIInterfaceOrientationPortrait;
}


// Only on iOS6
- (BOOL)shouldAutorotate
{
    return NO;
}
// Only on iOS6
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}





- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
